package cn.com.git.example.common;

import cn.com.git.example.common.util.object.MapperFacadeUtils;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import ma.glasnost.orika.MapperFacade;

import java.util.List;

public class ResultMsgFactory {

    /**
     * pageInfo 转换 ResultPage
     * 简单的转换
     * @param source 源 数据类型
     * @param tClass 目标数据类型
     * @param <TARGET> 目标
     * @param <SOURCE> 源
     * @return
     */
    public static <TARGET, SOURCE> ResultPage transfer(PageInfo<SOURCE> source, Class<TARGET> tClass) {
        if (source == null) {
            return null;
        }
        try {
            List<SOURCE> sList = source.getList();
            List<TARGET> tList = MapperFacadeUtils.mapList(sList, tClass);
            ResultPage resultPage = new ResultPage(ResultConstant.SUCCESS);
            resultPage.setPage(source.getPageNum());
            resultPage.setRecords(source.getTotal());
            resultPage.setRows(tList);
            resultPage.setTotal(source.getPages());
            return resultPage;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    /**
     * pageInfo 转换 ResultPage
     * 赋值数据集转换
     * 在数据集转换复杂的情况下用
     * @param source 源数据类型
     * @param tList 目标数据
     * @param <TARGET> 目标
     * @param <SOURCE> 源
     * @return
     */
    public static <TARGET, SOURCE> ResultPage transfer(PageInfo<SOURCE> source, List<TARGET> tList) {
        if (source == null) {
            return null;
        }
        try {
            ResultPage resultPage = new ResultPage(ResultConstant.SUCCESS);
            resultPage.setPage(source.getPageNum());
            resultPage.setRecords(source.getTotal());
            resultPage.setRows(tList);
            resultPage.setTotal(source.getPages());
            return resultPage;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

}
